package priv.yiyuan.example.composite.approvar1;

import java.util.ArrayList;
import java.util.List;

/**
 * 部门
 * <p>
 * 组合模式-组件节点
 *
 * @author YiYuan
 * @data 2025/8/29
 * @apoNote
 */
public class Department implements Approver {

    private String name;

    private List<Approver> children;

    private double departmentApprovalLimit;

    public Department(String name, double departmentApprovalLimit) {
        this.name = name;
        this.departmentApprovalLimit = departmentApprovalLimit;
        this.children = new ArrayList<>();
    }

    @Override
    public void processRequest(ApprovalRequest request) {
        System.out.println("部门 " + name + " 正在尝试处理请求: " + request);
        boolean handled = false;
        if (request.getAmount() <= departmentApprovalLimit) {
            for (Approver approver : children) {
                if (request.getAmount() <= approver.getApprovalLimit()) {
                    approver.processRequest(request);
                    handled = true;
                    break;
                }
            }
            if (!handled) {
                System.out.println(" 部门 " + name + " 内部没有找到合适的审批者处理此请求。");
            }
        }
        else {
            System.out.println("  部门 " + name + " 无法处理此请求(超出部门限额: " + departmentApprovalLimit + ")。");
        }
    }

    @Override
    public void add(Approver approver) {
        children.add(approver);
        System.out.println(
                approver.getClass().getSimpleName()
                        + " " +
                        ((approver instanceof Employee) ? ((Employee) approver).getName() : ((Department) approver).getName())
                        + " 已加入 " +
                        name
                        + " 部门。"
        );
    }

    @Override
    public void remove(Approver approver) {
        children.remove(approver);
        System.out.println(
                approver.getClass().getSimpleName()
                        + " " +
                        ((approver instanceof Employee) ? ((Employee) approver).getName() : ((Department) approver).getName())
                        + " 已从 " +
                        name
                        + " 部门移除。"
        );
    }

    @Override
    public double getApprovalLimit() {
        return this.departmentApprovalLimit;
    }

    public String getName() {
        return this.name;
    }
}
